using DG.Tweening;
using System.Collections;
using UnityEngine;

public class FreeListObj : MonoBehaviour
{
    [SerializeField] private float lifeTime = -1;
    protected Vector3 playerSpriteOffset = new(0, 0.9f);

    private void OnEnable()
    {
        if (lifeTime != -1)
        {
            SetLifeTime(lifeTime);
        }
    }

    public void SetLifeTime(float time)
    {
        lifeTime = time;
        if (time > 0) StartCoroutine(ReturnToPoolAfterTime());
        else StopAllCoroutines();
    }

    public void AddLifeTime(float time)
    {
        if (lifeTime > 0) lifeTime += time;
        else
        {
            Debug.LogWarning("FreeListObj: AddLifeTime failed, lifeTime is not set.");
        }
    }
    public float GetLifeTime()
    {
        return lifeTime;
    }

    public virtual void Destroy()
    {
        FreeList.Instance.PushObject(gameObject);
        DOTween.Kill(transform);
        foreach (Transform child in transform.GetComponentsInChildren<Transform>()) DOTween.Kill(child);
    }

    private void OnDestroy()
    {
        DOTween.Kill(transform);
        foreach (Transform child in transform.GetComponentsInChildren<Transform>()) DOTween.Kill(child);
    }

    protected IEnumerator ReturnToPoolAfterTime()
    {
        float timer = 0f;
        while (true)
        {
            if (timer >= lifeTime)
            {
                Destroy();
                yield break;
            }
            timer += Time.deltaTime;
            yield return null;
        }
    }
}
